﻿
using System.Text;
using Protocol.SouthGridProtocol.Blocks;
using Protocol.SouthGridProtocol.Decoder;
using Protocol.SouthGridProtocol.Encoder;
using PacoToolKit.Format;
namespace Protocol.SouthGridProtocol.Model
{
    public class C10H
    {
        private static string afn = "10";
        private static string head = "68";
        private static string bottom = "16";

        private static Seq seq = new Seq(0, 1, 1, 1, 7);
        private static C c = new C(0, 1, 1, null, 0, 11);//prm=1,funcode=11


        /// <summary>
        /// 组成下发中继的报文
        /// </summary>
        /// <param name="concentrator"></param>
        /// <param name="data">di:E3020001 的数据内容</param>
        /// <returns></returns>
        public static string encodeC10H(string concentrator, string data)
        {
            //主站启动的发送帧的MSA应为非零值,终端启动发送帧的MSA应为零，其主站响应帧的MSA也应为零
            concentrator = concentrator.Substring(0, 12) + "01";
            StringBuilder sb = new StringBuilder();
            sb.Append("0000" + Formater.ReverseHexString("E3020001") + data);
            StringBuilder msgsb = new StringBuilder();
            string length = BaseEncoder.CalcLength(c.encodeC() + concentrator + afn + seq.encodeSeqString() + sb.ToString());
            string cs = BaseEncoder.CalcCSCode(c.encodeC() + concentrator + afn + seq.encodeSeqString() + sb.ToString());
            return head + length + length + head + c.encodeC() + concentrator + afn + seq.encodeSeqString() + sb.ToString() + cs + bottom;
        }
        /// <summary>
        /// 获取上报的中继数据域内容
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static string decodeC10H(string msg)
        {
            int msgLength = BaseDecoder.GetLength(msg);//字节数
            int dataRemainLen = (msgLength - 10) * 2;//初始 剩余未读数据长度
            string dataRemain = msg.Substring(32, dataRemainLen);//初始 剩余未读数据
            return dataRemain.Remove(0, 12);//剔除da,di，留下data
        }
    }
}
